<template>
  <a-modal v-model="showModal" width="860px" :title="title" :confirm-loading="loading" @ok="submit">
    <a-spin :spinning="loading" :tip="step === 0 ? undefined : '结算中...'">
      <section style="padding-right: 8px; height: calc(100vh - 448px); overflow: auto">
        <a-steps style="width: 80%" class="m-auto mb-24" v-model="step">
          <a-step title="填写取消政策信息"></a-step>
          <a-step disabled title="填写政策内容"></a-step>
        </a-steps>
        <a-form v-show="step === 0" style="width: 80%" :form="form" class="inline-form m-auto mt-24">
          <a-form-item label="取消政策名称：">
            <a-input
              class="w-full"
              placeholder="请输入取消政策名称"
              v-decorator="['name', { rules: [{ required: true, message: '请输入取消政策名称' }] }]"
            />
          </a-form-item>
          <a-form-item label="取消政策类型：">
            <a-select
              class="w-full"
              placeholder="请取消政策类型"
              v-decorator="['type', { rules: [{ required: true, message: '请选择取消政策类型' }] }]"
            >
              <a-select-option v-for="item in typeList" :value="item.value" :key="item.value">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="取消政策描述：">
            <a-textarea
              class="w-full"
              :max-length="300"
              placeholder="请输入取消政策描述"
              v-decorator="['desc', { rules: [{ required: true, whitespace: true, message: '请输入取消政策描述' }] }]"
            />
          </a-form-item>
        </a-form>
        <!-- <a-alert v-show="step === 1" style="width: 90%" class="m-auto" type="info" show-icon :message="`{{123}}`" /> -->
        <a-alert v-if="step !== 0" style="width: 90%" class="m-auto" type="info" show-icon>
          <span slot="message">
            <span>正在为</span>
            <span class="font-bold text-16">{{ cancelInfo.name }}</span>
            <span class="font-bold text-16">({{ cancelInfo.typename }})</span>
            <span>完善取消政策内容</span>
          </span>
        </a-alert>
        <div v-show="step === 1" class="mt-10">
          <section class="flex items-center">
            <a-button
              v-if="$permissionJudge('CancelStrategyAddRule')"
              type="primary"
              icon="plus"
              @click="$refs.addCancelRules.open((id = ''))"
              >新建取消政策</a-button
            >
          </section>
          <a-table class="mt-16" :columns="columns" :data-source="data" :pagination="pagination">
            <template #time="val, data">
              <section class="text-14" v-if="data.isSpecialTime">{{ data.startTime }}至{{ data.endTime }}</section>
              <section class="text-14" v-if="!data.isSpecialTime">日常使用</section>
              <section class="text-14">
                {{ data.isSpecialTime ? data.specialTimeName : '除特殊指定的时间外适用' }}
              </section>
            </template>
            <template #cancelRules="val, data">
              <section v-for="(item, index) in data.cancelRules">
                <!-- <section class="text-14">取车时间{{ item.hours }},{{ item.fee }}</section> -->
                <!-- <section class="text-14">{{item.hours>0?取车时间前item.hours个小时内取消，需支付预定金额的80%为取消费用:取车时间之后取消，需支付预定金额的item.fee%为取消费用}}</section> -->
                <section class="text-14 w-auto" v-if="item.hours >= 0">
                  取车时间{{ item.hours }}个小时前取消，需支付预定金额的{{ item.fee }}%为取消费用
                </section>
                <section class="text-14 w-auto" v-if="item.hours < 0">
                  取车时间之后取消，需支付预定金额的{{ item.fee }}%为取消费用
                </section>
              </section>
            </template>
            <template #action="val, data">
              <a
                class="action w-auto"
                v-if="$permissionJudge('CancelStrategyUpdateRule')"
                @click="$refs.addCancelRules.open((id = data.id), data)"
                >修改政策</a
              >
              <a
                class="action rd w-auto mt-10"
                v-if="$permissionJudge('CancelStrategyDeleteRule')"
                @click="deleteData(data)"
                >删除
              </a>
            </template>
          </a-table>
        </div>
      </section>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">{{ step == 1 ? '上一步' : '取消' }} </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
        {{ step == 1 ? '完成' : '下一步' }}</a-button
      >
    </template>
    <AddCancelRules ref="addCancelRules" @success="success" :cancelStrategyId="cancelStrategyId" />
  </a-modal>
</template>

<script>
import { add, list, getRuleList, deleteRule, update } from '@/api/cancel-policy'
import AddCancelRules from './AddCancelRules'
import { tableMixins } from '@/utils/mixins'

export default {
  components: { AddCancelRules },
  props: {
    // Canceltype: {
    //   type: String,
    // },
    cancelStrategydata: {
      type: Array,
    },
  },
  mixins: [tableMixins],
  data() {
    return {
      loading: false,
      showModal: false,
      step: 0,
      pageNum: 1,
      rowsNum: 10,
      form: this.$form.createForm(this),
      formData: {},
      typeList: [],
      cancelStrategyId: '',
      data: [],
      title: '',
      Canceltype: '',
      cancelInfo: {},
      columns: [
        { dataIndex: 'time', title: '取消适用时间', align: 'center', scopedSlots: { customRender: 'time' } },
        { dataIndex: 'cancelFeeText', title: '取消费用收取方式', align: 'center' },
        {
          dataIndex: 'cancelRules',
          title: '具体费用规则',
          align: 'center',
          width: 300,
          scopedSlots: { customRender: 'cancelRules' },
        },
        {
          title: '操作',
          fixed: 'right',
          dataIndex: 'action',
          width: 160,
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      cancelTypeList: [],
      info: {},
    }
  },
  computed: {},
  watch: {
    showModal() {
      this.step = 0
      this.form.resetFields()
      this.formData = {}
    },
  },
  created() {
    this.$utils.getDictList('CancelType').then((res) => {
      this.cancelTypeList = res
      console.log(res)
    })
  },
  mounted() {},
  destroyed() {},
  methods: {
    open(type, item) {
      console.log(item)
      console.log(type)
      console.log(this.step)
      this.Canceltype = type
      this.showModal = true
      this.getList()
      if (type == 2) {
        this.title = '新建取消政策'
      } else if (type == 1) {
        console.log(item)
        this.cancelInfo = item
        this.Info = item
        this.cancelStrategyId = item.id
        this.title = '更新取消政策'
        this.$nextTick(() => {
          this.form.setFieldsValue({
            name: item.name,
            type: item.type,
            desc: item.desc,
          })
        })
      }
    },
    getList() {
      this.$utils.getDictList('CancelStrategyType').then((res) => {
        //取消规则类型
        this.typeList = res
        console.log(res)
      })
    },
    getData() {
      this.loading = true
      return getRuleList({
        pageNo: this.pageNum,
        pageSize: this.rowsNum,
        cancelStrategyId: this.cancelStrategyId,
      })
        .then((data) => {
          data.items.map((v) => {
            this.cancelTypeList.map((j) => {
              if (v.cancelFeeType == j.value) {
                v.cancelFeeText = j.name
              }
            })
          })
          this.data = data.items
          this.total = data.rowCount
        })
        .finally(() => (this.loading = false))
    },
    handleOk() {
      console.log(this.step)
      if (this.step === 0) {
        this.form.validateFields(async (err, values) => {
          if (!err) {
            this.formData = values
            this.loading = true
            const id = this.cancelStrategyId
            const fun = this.Canceltype == 2 ? add : update
            fun({
              ...values,
              id,
            })
              .then((res) => {
                console.log(res)
                this.$message.success(id ? '编辑成功！' : '新建成功！')
                this.getcancelStrategyList()
                this.getData()
                // this.form.resetFields()
                this.step = 1
                this.$emit('success')
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
      } else {
        this.$message.success('保存成功')
        this.showModal = false
      }
    },
    handleCancel() {
      console.log(this.step)
      if (this.step == 1) {
        this.step = 0
      } else {
        this.showModal = false
      }
    },
    success() {
      this.getData()
    },
    deleteData(data) {
      this.$confirm({
        title: '提示',
        content: `确定要删除此条规则吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          if (this.loading) return false
          this.loading = true
          deleteRule({ id: data.id })
            .then(() => {
              this.$message.success('删除成功！')
              this.getData()
            })
            .finally(() => {
              this.loading = false
            })
        },
      })
    },
    getcancelStrategyList() {
      list().then((data) => {
        data.map((v) => {
          if (v.id == this.cancelInfo.id) {
            this.cancelInfo.name = v.name
          }
        })
      })
    },
  },
}
</script>
<style scoped lang='less'>
.action {
  display: block;
}
.rd {
  color: red;
}
.w-auto {
  width: auto;
  margin-bottom: 10px;
}
</style>
